/* Gauge - Performance Measurement Framework for Mobile Platforms
 * Copyright (C) 2013, Juha Hytonen <juha.a.hytonen@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.gauge.ExampleBenchmarks.Workloads;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;

import org.gauge.ExampleBenchmarks.R;

/**
 * Simple service that plays a predefined song.
 */
public final class MusicPlaybackService extends Service implements Runnable, MediaPlayer.OnCompletionListener {
	
	private boolean terminate;
	private Thread thread;
	private MediaPlayer mediaPlayer;

	@Override
	public void onCreate() {
		super.onCreate();
		terminate = false;
		thread = new Thread(this);
		mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.downtown);
		mediaPlayer.setOnCompletionListener(this);
	}
	
	@Override
	public void onDestroy() {
		terminate();
	}
	
	synchronized private void terminate() {
		terminate = true;
		notify();
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		thread.start();
		return Service.START_STICKY;
	}
	
	@Override
	public void onCompletion(MediaPlayer mediaPlayer) {
		terminate();
	}
	
	@Override
	public void run() {
		mediaPlayer.start();
		while (!terminate) {
			try {
				synchronized(this) {
					wait();
				}
			}
			catch(InterruptedException e) {
			}
		}
		mediaPlayer.release();
		stopSelf();
	}
	
}
